<template>
	<view class="container">
		<!-- 头部 -->
		<view class="header">
			<!-- 编辑按钮 -->
			<view class="edit-btn" v-if="!isEditing" @click="handleEdit">
				<uni-icons type="compose" size="24" color="#555"></uni-icons>
			</view>

			<!-- 用户头像 -->
			<view class="avatar-container" @click="isEditing ? chooseAvatar() : null">
				<image class="avatar" :src="editForm.avatar || '/static/avatar/empty.png'" mode="aspectFill">
				</image>
				<view v-if="isEditing" class="change-avatar-btn" @click.stop="chooseAvatar">
					<text>更换头像</text>
				</view>
			</view>
		</view>

		<!-- 编辑操作按钮 - 与编辑按钮相同样式 -->
		<view v-if="isEditing" class="edit-actions">
			<view class="action-btn save-btn" @click="saveChanges">
				<uni-icons type="checkmarkempty" size="24" color="#4CAF50"></uni-icons>
			</view>
			<view class="action-btn cancel-btn" @click="handleCancel">
				<uni-icons type="closeempty" size="24" color="#F44336"></uni-icons>
			</view>
		</view>

		<!-- 基本信息卡片 -->
		<view class="info-card">
			<view class="card-header">
				<uni-icons type="person" size="18" color="#ffffff"></uni-icons>
				<text class="card-title">基本信息</text>
			</view>
			<view class="info-item">
				<text class="info-label">姓名</text>
				<text class="info-value">{{ editForm.username }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">性别</text>
				<view class="info-value">
					<picker mode="selector" :range="genderList" :value="editForm.gender" v-if="isEditing"
						@change="onGenderChange">
						{{ genderList[editForm.gender] }}
					</picker>
					<text v-else>{{ formatGender(editForm.gender) }}</text>
				</view>
			</view>

			<view class="info-item">
				<text class="info-label">用户状态</text>
				<text class="info-value">
					<text class="status-badge"
						:class="'status-' + editForm.status">{{ formatStatus(editForm.status) }}</text>
				</text>
			</view>
			<view class="info-item">
				<text class="info-label">注册时间</text>
				<text class="info-value">{{ formatDate(editForm.register_date) }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">备注</text>
				<view class="info-value">
					<input v-if="isEditing" v-model="editForm.comment" placeholder="请输入备注" />
					<text v-else>{{ editForm.comment || '无' }}</text>
				</view>
			</view>
		</view>

		<!-- 联系方式卡片 -->
		<view class="info-card">
			<view class="card-header">
				<uni-icons type="phone" size="18" color="#ffffff"></uni-icons>
				<text class="card-title">联系方式</text>
			</view>
			<view class="info-item">
				<text class="info-label">手机</text>
				<text class="info-value">{{ editForm.mobile }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">短码</text>
				<view class="info-value">
					<input v-if="isEditing" v-model.number="editForm.short" type="digit" placeholder="请输入短码" />
					<text v-else>{{ editForm.short || '未设置' }}</text>
				</view>
			</view>
			<view class="info-item">
				<text class="info-label">座机</text>
				<view class="info-value">
					<input v-if="isEditing" v-model="editForm.phone" type="number" placeholder="请输入座机号码" />
					<text v-else>{{ editForm.phone || '未设置' }}</text>
				</view>
			</view>
		</view>

		<!-- 组织信息卡片 -->
		<view class="info-card">
			<view class="card-header">
				<uni-icons type="staff" size="18" color="#ffffff"></uni-icons>
				<text class="card-title">组织信息</text>
			</view>
			<view class="info-item">
				<text class="info-label">部门</text>
				<view class="info-value">
					<view class="tag-container">
						<text class="tag">{{ editForm.d_ids.text }}</text>
					</view>
				</view>
			</view>
			<view class="info-item">
				<text class="info-label">职务</text>
				<view class="info-value">
					<view class="tag-container">
						<text class="tag">{{ editForm.j_ids.text }}</text>
					</view>
				</view>
			</view>
			<view class="info-item">
				<text class="info-label">用户角色</text>
				<view class="info-value">
					<view class="tag-container">
						<text class="tag">{{ editForm.role.text }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 登录信息卡片 -->
		<view class="info-card">
			<view class="card-header">
				<uni-icons type="clock" size="18" color="#ffffff"></uni-icons>
				<text class="card-title">登录信息</text>
			</view>
			<view class="info-item">
				<text class="info-label">注册信息</text>
				<view class="info-value">
					<view class="time-info">
						<view class="time-item">
							<text class="time-label">注册时间:</text>
							<text class="time-value">{{ formatDate(userInfo.register_date) }}</text>
						</view>
						<view class="time-item">
							<text class="time-label">注册IP:</text>
							<text class="time-value">{{ userInfo.register_ip || '未知' }}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="info-item">
				<text class="info-label">最后登录:</text>
				<view class="info-value">
					<view class="time-info">
						<view class="time-item">
							<text class="time-label">登录时间:</text>
							<text class="time-value">
								{{ userInfo.last_login_date ? formatDate(userInfo.last_login_date) : '从未登录' }}
							</text>
						</view>
						<view class="time-item">
							<text class="time-label">登录IP:</text>
							<text class="time-value">{{ userInfo.last_login_ip || '未知' }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isEditing: false,
				userInfo: {
					avatar: ''
				},
				editForm: {
					avatar: '',
					comment: '',
					short: '',
					phone: '',
					gender: 0,
					d_ids: {
						value: '',
						text: ''
					},
					j_ids: {
						value: '',
						text: ''
					}
				},
				genderList: ['未知', '男', '女'],
				originalUserInfo: {}, // 用于保存原始数据副本
				avatar: "/static/avatar/empty.png",
			}
		},
		onLoad() {
			this.userInfo = uni.getStorageSync('userInfo');
			this.initEditForm();
		},
		onUnload() {
			if (this.isEditing && !this.isEqual(this.editForm, this.originalUserInfo)) {
				uni.showModal({
					title: '提示',
					content: '检测到修改，是否保存？',
					success: (res) => {
						if (res.confirm) {
							this.saveChanges();
						} else if (res.cancel) {
							this.editForm = JSON.parse(JSON.stringify(this.originalUserInfo));
						}
					}
				});
			}
		},
		methods: {
			formatGender(gender) {
				const genders = {
					0: '未知',
					1: '男',
					2: '女'
				};
				return genders[gender] || '未知';
			},
			formatStatus(status) {
				const statuses = {
					0: '正常',
					1: '禁用',
					2: '审核中',
					3: '审核拒绝'
				};
				return statuses[status] || '未知状态';
			},
			isEqual(obj1, obj2) {
				return JSON.stringify(obj1) === JSON.stringify(obj2);
			},
			getChangedFields(original, current) {
				const changes = {};
				Object.keys(current).forEach(key => {
					if (key === '_id') return;

					if (typeof current[key] === 'object' && current[key] !== null && !Array.isArray(current[
							key])) {
						const subChanges = this.getChangedFields(original[key] || {}, current[key]);
						if (Object.keys(subChanges).length > 0) {
							changes[key] = subChanges;
						}
					} else if (JSON.stringify(original[key]) !== JSON.stringify(current[key])) {
						changes[key] = current[key];
					}
				});
				return changes;
			},
			saveChanges() {
				const _id = this.editForm._id;
				const changedData = this.getChangedFields(this.originalUserInfo, this.editForm);

				if (Object.keys(changedData).length === 0) {
					uni.showToast({
						title: '没有修改内容',
						icon: 'none'
					});
					return;
				}

				const obj = uniCloud.importObject('users');
				obj.updateUserInfo({
					_id,
					data: changedData
				}).then(res => {
					if (res.code === 0) {
						const newUserInfo = {
							...this.userInfo,
							...changedData
						};
						uni.setStorageSync('userInfo', newUserInfo);
						this.userInfo = newUserInfo;
						this.originalUserInfo = JSON.parse(JSON.stringify(this.editForm));
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
						this.isEditing = false;
					} else {
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				});
			},
			handleEdit() {
				this.isEditing = true;
			},
			handleCancel() {
				const hasChanges = !this.isEqual(this.editForm, this.originalUserInfo);
				if (hasChanges) {
					uni.showModal({
						title: '提示',
						content: '是否放弃当前修改？',
						success: (res) => {
							if (res.confirm) {
								this.editForm = JSON.parse(JSON.stringify(this.originalUserInfo));
								this.isEditing = false;
							}
						}
					});
				} else {
					this.isEditing = false;
				}
			},
			async chooseAvatar() {
				if (!this.isEditing) return;

				try {
					const res = await uni.chooseImage({
						count: 1,
						sourceType: ['album', 'camera']
					});
					const tempFilePath = res.tempFilePaths[0];

					// 从文件路径中提取文件名（兼容小程序）
					const fileName = tempFilePath.substring(tempFilePath.lastIndexOf('/') + 1);
					console.log(fileName, 'upload');

					// 获取文件后缀
					const fileExt = this.getFileExtension(fileName) || 'jpg';

					uni.showToast({
						title: '上传中...',
						icon: 'loading'
					});

					const mobile = this.userInfo.mobile;
					const uploadResult = await uniCloud.uploadFile({
						cloudPathAsRealPath: true,
						cloudPath: `avatars/${mobile}/${Date.now()}.${fileExt}`,
						filePath: tempFilePath
					});

					if (!uploadResult || !uploadResult.fileID) {
						throw new Error('上传失败');
					}

					const fileUrlResult = await uniCloud.getTempFileURL({
						fileList: [uploadResult.fileID]
					});
					const avatarUrl = fileUrlResult.fileList[0].tempFileURL;

					this.editForm.avatar = avatarUrl;
					this.userInfo.avatar = avatarUrl;

					uni.showToast({
						title: '上传成功',
						icon: 'success'
					});

				} catch (err) {
					console.error(err);
					uni.showToast({
						title: '选择或上传失败',
						icon: 'none'
					});
				}
			},

			// 新增方法：提取文件后缀
			getFileExtension(filename) {
				// 处理带查询参数的情况（如：https://example.com/image.png?width=200）
				// const cleanName = filename.split('?')[0];
				const parts = filename.split('.');
				console.log(parts, '文件名')
				if (parts.length > 1) {
					return parts.pop().toLowerCase();
				}
				return null;
			},
			initEditForm() {
				this.editForm = JSON.parse(JSON.stringify({
					...this.userInfo,
					avatar: this.userInfo.avatar || this.avatar,
					comment: this.userInfo.comment || '',
					short: this.userInfo.short || '',
					phone: this.userInfo.phone || '',
					gender: this.userInfo.gender || 0,
					d_ids: this.userInfo.d_ids || {
						value: '',
						text: ''
					},
					j_ids: this.userInfo.j_ids || {
						value: '',
						text: ''
					}
				}));
				this.originalUserInfo = JSON.parse(JSON.stringify(this.editForm));
			},
			onGenderChange(e) {
				const index = e.detail.value;
				this.editForm.gender = index;
			},
			// 修改 formatDate 方法
			formatDate(timestamp) {
				if (!timestamp) return '未知';

				// 处理不同格式的日期字符串
				let date;
				if (typeof timestamp === 'string') {
					// 替换空格为 T 的格式（ISO 8601）
					if (timestamp.includes(' ')) {
						timestamp = timestamp.replace(' ', 'T');
					}
					// 处理无时区的日期格式
					if (!timestamp.includes('+') && !timestamp.includes('Z') && timestamp.includes('T')) {
						timestamp += 'Z'; // 添加 UTC 时区标识
					}
				}

				// 尝试创建 Date 对象
				try {
					date = new Date(timestamp);
					// 检查日期是否有效
					if (isNaN(date.getTime())) {
						throw new Error('Invalid date');
					}
				} catch (e) {
					// 如果解析失败，尝试其他格式
					if (typeof timestamp === 'string') {
						// 尝试斜杠格式
						if (timestamp.includes('-')) {
							timestamp = timestamp.replace(/-/g, '/');
						}
						date = new Date(timestamp);
						if (isNaN(date.getTime())) {
							return '未知';
						}
					} else {
						return '未知';
					}
				}

				// 格式化日期
				const pad = (n) => n.toString().padStart(2, '0');
				return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #f5f7fa;
		color: #333;
		padding: 40rpx 20rpx 20rpx;
		max-width: 1200rpx;
		margin: 0 auto;
	}

	.header {
		text-align: center;
		padding: 60rpx 0 30rpx;
		position: relative;
	}

	.edit-btn {
		position: absolute;
		right: 30rpx;
		top: 60rpx;
		z-index: 10;
		background: rgba(255, 255, 255, 0.9);
		border-radius: 50%;
		width: 70rpx;
		height: 70rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
		overflow: hidden;
		/* 确保背景保持圆形 */
	}

	.edit-btn:active {
		transform: scale(0.95);
		background: rgba(200, 200, 200, 0.9);
	}

	/* 编辑操作按钮样式 - 与编辑按钮相同样式 */
	.edit-actions {
		position: absolute;
		right: 30rpx;
		top: 140rpx;
		/* 在编辑按钮下方 */
		z-index: 10;
		display: flex;
		flex-direction: column;
		/* 纵向排列 */
		gap: 20rpx;
	}

	.action-btn {
		background: rgba(255, 255, 255, 0.9);
		border-radius: 50%;
		width: 70rpx;
		height: 70rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
		overflow: hidden;
		/* 修复背景变形问题 */
	}

	.save-btn:active {
		background: rgba(76, 175, 80, 0.2);
	}

	.cancel-btn:active {
		background: rgba(244, 67, 54, 0.2);
	}

	/* 添加点击动画效果 */
	.save-btn:active,
	.cancel-btn:active {
		transform: scale(0.95);
	}

	.avatar-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 50rpx;
	}

	.avatar {
		width: 200rpx;
		height: 200rpx;
		border-radius: 50%;
		border: 6rpx solid #fff;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
		background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
	}

	/* 更换头像按钮样式 - 在头像下方 */
	.change-avatar-btn {
		margin-top: 20rpx;
		padding: 8rpx 20rpx;
		background-color: #5555ff;
		color: white;
		border-radius: 40rpx;
		font-size: 24rpx;
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
		transition: all 0.2s ease;
	}

	.change-avatar-btn:active {
		background-color: #4444ee;
		transform: translateY(4rpx);
	}

	/* 更换头像按钮样式 - 在头像下方 */
	.change-avatar-btn {
		margin-top: 20rpx;
		padding: 8rpx 20rpx;
		background-color: #5555ff;
		color: white;
		border-radius: 40rpx;
		font-size: 24rpx;
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
		transition: all 0.2s ease;
	}

	.change-avatar-btn:active {
		background-color: #4444ee;
		transform: translateY(4rpx);
	}

	.camera-icon {
		position: absolute;
		bottom: 10rpx;
		right: 10rpx;
		background: rgba(0, 0, 0, 0.6);
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 2rpx solid #fff;
	}

	.info-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.05);
		margin-bottom: 40rpx;
		overflow: hidden;
		transition: transform 0.3s ease;
	}

	.card-header {
		padding: 32rpx 40rpx;
		background-color: #5555ff;
		border-bottom: 2rpx solid #eaeaea;
		font-weight: 600;
		color: #2979ff;
		display: flex;
		align-items: center;
	}

	.card-header uni-icons {
		margin-right: 16rpx;
	}

	.card-header .card-title {
		color: #ffffff;
	}

	.info-item {
		display: flex;
		padding: 32rpx 40rpx;
		border-bottom: 2rpx solid #f1f1f1;
	}

	.info-item:last-child {
		border-bottom: none;
	}

	.info-label {
		width: 200rpx;
		color: #7f8c8d;
		font-size: 28rpx;
		flex-shrink: 0;
	}

	.info-value {
		flex: 1;
		color: #2c3e50;
		font-size: 24rpx;
		font-weight: 500;
		word-break: break-all;
	}

	input {
		font-size: 24rpx;
		padding: 8rpx 0;
		border-bottom: 1rpx solid #ccc;
	}

	picker {
		font-size: 24rpx;
		color: #2c3e50;
	}

	.status-badge {
		display: inline-block;
		padding: 8rpx 20rpx;
		border-radius: 40rpx;
		font-size: 24rpx;
		font-weight: 500;
	}

	.status-0 {
		background-color: #e8f5e9;
		color: #2e7d32;
	}

	.status-1 {
		background-color: #ffebee;
		color: #c62828;
	}

	.status-2 {
		background-color: #fff8e1;
		color: #f57f17;
	}

	.status-3 {
		background-color: #f5f5f5;
		color: #616161;
	}

	.tag-container {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}

	.tag {
		background-color: #e3f2fd;
		color: #1976d2;
		padding: 8rpx 20rpx;
		border-radius: 40rpx;
		font-size: 24rpx;
	}

	.time-info {
		display: flex;
		flex-wrap: wrap;
		gap: 30rpx;
	}

	.time-item {
		background: #f8f9fa;
		padding: 16rpx 24rpx;
		border-radius: 16rpx;
		flex: 1;
		min-width: 280rpx;
	}

	.time-label {
		font-size: 24rpx;
		color: #7f8c8d;
		margin-bottom: 8rpx;
		margin-right: 10rpx;
	}

	.time-value {
		font-size: 24rpx;
		font-weight: 500;
		color: #2c3e50;
		margin-left: 10rpx;
	}

	@media (max-width: 768px) {
		.edit-actions {
			padding: 0 40rpx;
			gap: 20rpx;
		}

		.action-btn {
			width: 90rpx;
			/* 新增 */
			height: 90rpx;
			font-size: 30rpx;
		}
	}
</style>